package com.smap.core;

/**
 * envelope class
 * 
 * @author shen
 * 
 */
public class Bbox {
	public Double minX = null;
	public Double maxX = null;
	public Double minY = null;
	public Double maxY = null;

	public boolean overlap(Bbox box2) { 

		if (minX == null || box2.minX == null) {
			return false;
		}

		if (box2.minX > maxX && box2.maxX > maxX) {
			return false;
		}
		if (box2.minX < minX && box2.maxX < minX) {
			return false;
		}
		if (box2.minY > maxY && box2.maxY > maxY) {
			return false;
		}
		if (box2.minY < minY && box2.maxY < minY) {
			return false;
		}

		return true;
	}

	public boolean contains(XY xy) {
		if (minX == null) {
			return false;
		}
		if ((xy.x < (minX - XY.TOLERANCE)) || (xy.y < (minY - XY.TOLERANCE))
				|| (xy.x > (maxX + XY.TOLERANCE))
				|| (xy.y > (maxY + XY.TOLERANCE))) {
			return false;
		}
		return true;
	}

	public Bbox expand(XY xy) {
		return this.expand(xy.x, xy.y);
	}

	public Bbox expand(double x, double y) {
		if (minX == null) {
			minX = x;
			maxX = x;
		} else {
			minX = Math.min(minX, x);
		}
		if (minY == null) {
			minY = y;
			maxY = y;
		} else {
			minY = Math.min(minY, y);
		}

		maxX = Math.max(maxX, x);
		maxY = Math.max(maxY, y);
		return this;
	}

	public void clear() {
		minX = null;
		minY = null;
		maxX = null;
		maxY = null;
	}

	@Override
	public String toString() {
		if (minX == null) {
			return "Null bbox";
		}
		return Math.round(minX) + "," + Math.round(minY) + ","
				+ Math.round(maxX) + "," + Math.round(maxY);
	}

	public XY getCentroid() {
		if (minX == null) {
			return null;
		}
		return new XY((minX + maxX) / 2, (minY + maxY) / 2);
	}
}
